<template>
	<view class="container">
		<view class="personal">
			<!-- 页面头部 -->
			<view class="header">
				<view class="title">
					<text>获取您的昵称、头像</text>
				</view>
				<view class="sub-title">
					<text>填写您的微信头像和昵称，以便获得更好的体验</text>
				</view>
			</view>
			<!-- 表单组件 -->
			<view class="login-form">
				<view class="form-item">
					<view class="form-item--label">头像</view>
					<button class="btn-normal" open-type="chooseAvatar" @click="onClickAvatar()"
						@chooseavatar="onChooseAvatar">
						<avatar-image :url="avatarUrl" :width="100" />
					</button>
				</view>
				<view class="form-item">
					<view class="form-item--label">昵称</view>
					<input class="form-item--input" type="nickname" v-model="form.nickname" maxlength="30"
						placeholder="请输入微信昵称" @input="onInputNickName" @blur="onInputNickName" />
				</view>
			</view>
			<!-- 操作按钮 -->
			<view class="login-btn">
				<view class="button" :class="{ disabled }" @click="handleSubmit()">确认</view>
			</view>
			<view class="no-login-btn">
				<view class="button" @click="handleCancel()">暂不登录</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	import store from '@/store'
	import * as LoginApi from '@/api/login'
	import * as UploadApi from '@/api/upload'
	import AvatarImage from '@/components/avatar-image'
	import storage from '@/utils/storage';
	import {
		isEmpty
	} from '@/utils/util'
	import * as Verify from '@/utils/verify'
	// import StoreModel from '@/common/model/Store'

	export default {
		components: {
			AvatarImage
		},
		data() {
			return {
				tempToken : "",
				// 是否需要填写用户昵称和头像
				isPersonal: true,

				// 微信小程序登录凭证 (code)
				// 提交到后端，用于换取openid
				code: '',
				// 按钮禁用
				disabled: false,
				// 头像路径 (用于显示)
				avatarUrl: '',
				// 临时图片 (用于上传)
				tempFile: undefined,
				// 表单数据
				form: {
					avatar: null,
					nickname: ''
				},
			}
		},

		created() {
		},

		methods: {

			// 绑定昵称输入框 (用于微信小程序端快速填写昵称能力)
			onInputNickName({
				detail
			}) {
				console.log(detail)
				if (detail.value) {
					this.form.nickname = detail.value
				}
			},

			// 点击头像按钮事件
			onClickAvatar() {
				// #ifdef MP-WEIXIN
				return
				// #endif
				this.chooseImage()
			},

			// 选择头像事件 - 仅限微信小程序
			onChooseAvatar({
				detail
			}) {
				// #ifdef MP-WEIXIN
				const app = this
				app.avatarUrl = detail.avatarUrl
				app.tempFile = {
					path: app.avatarUrl
				}
				// #endif
			},

			// 选择图片
			chooseImage() {
				const app = this
				// 选择图片
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success({
						tempFiles
					}) {
						app.tempFile = tempFiles[0]
						app.avatarUrl = app.tempFile.path
					}
				});
			},

			// 上传图片
			uploadFile() {
				const app = this
				return UploadApi.image([app.tempFile])
					.then(fileIds => {
						 app.form.avatar = fileIds[0].data.url
						 app.tempFile = null
						return true
					})
					.catch((e) => {
						console.log(e)
						// app.disabled = false
						return false
					})
			},

			// 确认提交头像昵称
			async handleSubmit() {
				const app = this
				console.log('handleSubmit', app.form, app.tempFile)
				if (app.disabled === true) {
					return
				}
				if (app.tempFile === undefined || Verify.isEmpty(app.form.nickname)) {
					app.$toast('请填写头像和昵称~')
					return
				}
				// 按钮禁用
				app.disabled = true
				// 先上传头像图片
				if (!await app.uploadFile()) {
					app.$toast('很抱歉，头像上传失败')
					app.disabled = false
					return
				} else {
					app.disabled = false
				}
				// 提交到后端
				app.onAuthSuccess({
					nickname: app.form.nickname,
					avatar: app.form.avatar
				})
			},

			// 一键登录按钮点击事件
			handleLogin() {
				// this.onAuthSuccess({ nickname: '微信用户', avatarUrl: '' })
				//this.onAuthSuccess({})
				const app = this
				wx.canIUse('getUserProfile') && wx.getUserProfile({
					lang: 'zh_CN',
					desc: '获取用户相关信息',
					success({
						userInfo
					}) {
						console.log('用户同意了授权')
						console.log('userInfo：', userInfo)
						// 授权成功事件
						//app.onAuthSuccess(userInfo)
						app.onAuthSuccess({})
					},
					fail() {
						console.log('用户拒绝了授权')
					}
				})
			},

			// 获取微信用户信息(新版)
			/*    getUserProfile() {
        const app = this
        wx.canIUse('getUserProfile') && wx.getUserProfile({
          lang: 'zh_CN',
          desc: '获取用户相关信息',
          success({ userInfo }) {
            console.log('用户同意了授权')
            console.log('userInfo：', userInfo)
            // 授权成功事件
            //app.onAuthSuccess(userInfo)
			 app.onAuthSuccess({})
          },
          fail() {
            console.log('用户拒绝了授权')
          }
        })
      }, */

			// 授权成功事件
			// 这里分为两个逻辑:
			// 1.将code和userInfo提交到后端，如果存在该用户 则实现自动登录，无需再填写手机号
			// 2.如果不存在该用户, 则显示注册页面, 需填写手机号
			// 3.如果后端报错了, 则显示错误信息
			async onAuthSuccess(userInfo) {
				const app = this
				if (app.disabled === true) {
					return
				}
				// 按钮禁用
				app.disabled = true
				uni.showLoading({
					title: "登陆中"
				})
				console.log(111)
				store.dispatch('updateUser', {
					  nickname: app.form.nickname,
					  avatar: app.form.avatar,
					  refereeId: store.getters.refereeId
					})
					.then(result => {
						if(result.code == 0)return this.$toast(result.msg);
						// 一键登录成功
						app.$toast("登录成功")
						// 跳转回原页面
						uni.hideLoading()
						setTimeout(() => uni.switchTab({
							url:"/pages/user/user"
						}), 2000)
					})
					.catch(err => {
						// 按钮可用
						app.disabled = false
						uni.hideLoading()
						const resultData = err.result.data
						// 显示错误信息
						if (isEmpty(resultData)) {
							app.$toast(err.result.message)
						}
						// 跳转回原页面
						if (resultData.isBack) {
							setTimeout(() => app.onNavigateBack(1), 2000)
						}
						// 判断还需绑定手机号
						if (resultData.isBindMobile) {
							app.onEmitSuccess(userInfo)
						}
					})
			},

			// 将oauth提交给父级
			// 这里要重新获取code, 因为上一次获取的code不能复用(会报错)
			async onEmitSuccess(userInfo) {
				const app = this
				app.$emit('success', {
					oauth: 'MP-WEIXIN', // 第三方登录类型: MP-WEIXIN
					code: await app.getCode(), // 微信登录的code, 用于换取openid
					userInfo // 微信用户信息
				})
			},

			/**
			 * 暂不登录
			 */
			handleCancel() {
				// 跳转回原页面
				this.onNavigateBack()
			},

			/**
			 * 登录成功-跳转回原页面
			 */
			onNavigateBack(delta = 1) {
				const pages = getCurrentPages()
				if (pages.length > 1) {
					uni.navigateBack({
						delta: Number(delta || 1)
					})
				} else {
					this.$navTo('pages/index/index')
				}
			}

		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 0 60rpx;
		font-size: 32rpx;
		background: #fff;
		min-height: 100vh;
	}

	.personal {

		// 页面头部
		.header {
			padding-top: 120rpx;
			margin-bottom: 60rpx;

			.title {
				margin-bottom: 20rpx;
				color: #191919;
				font-size: 44rpx;
			}

			.sub-title {
				margin-bottom: 70rpx;
				color: #b3b3b3;
				font-size: 28rpx;
			}
		}

		.login-form {
			margin-bottom: 90rpx;
		}

		// 输入框元素
		.form-item {
			display: flex;
			align-items: center;
			padding: 18rpx;
			border-bottom: 1rpx solid #f3f1f2;
			margin-bottom: 30rpx;
			min-height: 96rpx;

			&--label {
				min-width: 150rpx;
				font-size: 28rpx;
				line-height: 50rpx;
			}

			&--input {
				font-size: 28rpx;
				letter-spacing: 1rpx;
				flex: 1;
				height: 100%;
			}

			&--parts {
				min-width: 100rpx;
			}

		}

	}

	.authorize {
		.store-info {
			padding: 80rpx 0 48rpx;
			border-bottom: 1rpx solid #e3e3e3;
			margin-bottom: 72rpx;
			text-align: center;

			.header {
				width: 190rpx;
				height: 190rpx;
				border: 4rpx solid #fff;
				margin: 0 auto 0;
				border-radius: 50%;
				overflow: hidden;
				box-shadow: 2rpx 0 10rpx rgba(50, 50, 50, 0.3);

				.image {
					display: block;
					width: 100%;
					height: 100%;
				}
			}
		}

		.auth-title {
			color: #585858;
			font-size: 34rpx;
			margin-bottom: 40rpx;
		}

		.auth-subtitle {
			color: #888;
			margin-bottom: 88rpx;
			font-size: 28rpx;
		}

	}

	.login-btn {
		margin-bottom: 20rpx;

		.button {
			width: 100%;
			height: 86rpx;
			background: linear-gradient(to right, #fa2209, #ff6335);
			color: #ffffff;
			font-size: 30rpx;
			border-radius: 80rpx;
			letter-spacing: 5rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			// 禁用按钮
			&.disabled {
				opacity: 0.6;
			}
		}
	}


	.no-login-btn {

		.button {
			height: 86rpx;
			background: #dfdfdf;
			color: #fff;
			font-size: 30rpx;
			border-radius: 80rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
</style>